<script lang="ts">
  import Tile from './Tile.svelte';
  let { tiles, inspectTile, selectInspectTile, zoomlevel, select, onKeyDown, fontFactor } = $props();
  let tileSelected = $state(false);
  let container: HTMLElement;
  let size = $derived(Math.floor(zoomlevel*(fontFactor ?? 1)));

  export const focus = () => {
    container.focus();
  }

  const hover = (tile) => {
    if (tileSelected && inspectTile === undefined) {
      tileSelected = false;
    }
    if (tile.stack.length === 0 || tileSelected)
      return;
    select(undefined);
    selectInspectTile(tile);
  };

  const click = (tile) => {
    if (tile.stack.length === 0)
      return;
    select(undefined);
    selectInspectTile(tile);
    tileSelected = true;
  };
</script>

<div bind:this={container} class="screen" tabindex="0" on:keypress={onKeyDown}>
  {#each tiles as line}
    <div class="line" style="height: {zoomlevel}px">
      {#each line as char}
        <Tile
          {char}
          {zoomlevel}
          {size}
          hover={() => hover(char)}
          click={() => click(char)}
          selected={inspectTile}
          />
      {/each}
    </div>
  {/each}
</div>

<style>
  .screen {
    padding: auto;
    margin: auto;
    align-self: center;
    vertical-align: center;
    align-content: center;
  }
  .screen:focus {
    outline: none;
  }
  .line {
    display: block;
  }
</style>
